const Plan = require('../models/Plan');
const Cadre = require('../models/Cadre');
const University = require('../models/University');

// 获取所有授课计划
const getAllPlans = async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      search, 
      teachingStatus, 
      teachingSemester,
      startDate,
      endDate,
      cadreId,
      universityId
    } = req.query;
    
    // 构建查询条件
    const query = {};
    if (teachingStatus) query.teachingStatus = teachingStatus;
    if (teachingSemester) query.teachingSemester = teachingSemester;
    if (cadreId) query.cadreId = cadreId;
    if (universityId) query.universityId = universityId;
    
    // 日期范围查询
    if (startDate || endDate) {
      query.classDate = {};
      if (startDate) query.classDate.$gte = new Date(startDate);
      if (endDate) query.classDate.$lte = new Date(endDate);
    }

    // 处理排序
    let sortObj = { classDate: -1 }; // 默认排序
    if (req.query.sortBy && req.query.sortOrder) {
        const sortBy = req.query.sortBy;
        const sortOrder = req.query.sortOrder === 'asc' ? 1 : -1;
        sortObj = { [sortBy]: sortOrder };
    }

    const plans = await Plan.find(query)
      .populate({
        path: 'cadreId',
        select: 'name position level',
        populate: {
          path: 'unitId',
          select: 'name shortName'
        }
      })
      .populate('universityId', 'schoolName location isCentral')
      .sort(sortObj)
      .limit(limit * 1)
      .skip((page - 1) * limit);

    // 如果有搜索条件，需要在populate后进行过滤
    let filteredPlans = plans;
    if (search) {
      filteredPlans = plans.filter(plan => 
        plan.courseName.includes(search) ||
        plan.location.includes(search) ||
        (plan.cadreId && plan.cadreId.name.includes(search)) ||
        (plan.universityId && plan.universityId.schoolName.includes(search))
      );
    }

    const total = await Plan.countDocuments(query);

    res.json({
      data: {
        plans: filteredPlans,
        totalPages: Math.ceil(total / limit),
        currentPage: parseInt(page),
        total
      },
      message: '获取授课计划列表成功'
    });
  } catch (error) {
    res.status(500).json({ error: '获取授课计划列表失败', message: error.message });
  }
};

// 根据ID获取授课计划
const getPlanById = async (req, res) => {
  try {
    const plan = await Plan.findById(req.params.id)
      .populate('cadreId')
      .populate('universityId')
      .populate({
        path: 'cadreId',
        populate: {
          path: 'unitId',
          select: 'name shortName'
        }
      });
    
    if (!plan) {
      return res.status(404).json({ error: '授课计划不存在' });
    }
    
    res.json({
      data: plan,
      message: '获取授课计划信息成功'
    });
  } catch (error) {
    res.status(500).json({ error: '获取授课计划信息失败', message: error.message });
  }
};

// 创建授课计划
const createPlan = async (req, res) => {
  try {
    console.log('接收到的授课计划数据:', req.body);

    // 验证干部是否存在
    const cadre = await Cadre.findById(req.body.cadreId);
    if (!cadre) {
      console.log('干部不存在:', req.body.cadreId);
      return res.status(400).json({ error: '授课干部不存在' });
    }

    // 验证高校是否存在
    const university = await University.findById(req.body.universityId);
    if (!university) {
      console.log('高校不存在:', req.body.universityId);
      return res.status(400).json({ error: '授课高校不存在' });
    }

    // 检查时间冲突
    const conflictPlan = await Plan.findOne({
      cadreId: req.body.cadreId,
      classDate: req.body.classDate,
      classTime: req.body.classTime,
      teachingStatus: { $nin: ['已取消'] }
    });

    if (conflictPlan) {
      return res.status(400).json({ error: '该干部在此时间已有授课安排' });
    }

    const plan = new Plan(req.body);
    await plan.save();
    
    // 返回包含关联数据的计划信息
    const populatedPlan = await Plan.findById(plan._id)
      .populate('cadreId')
      .populate('universityId')
      .populate({
        path: 'cadreId',
        populate: {
          path: 'unitId',
          select: 'name shortName'
        }
      });
    
    res.status(201).json({
      data: populatedPlan,
      message: '创建授课计划成功'
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      return res.status(400).json({ error: '数据验证失败', message: error.message });
    }
    if (error.code === 11000) {
      return res.status(400).json({ error: '该干部在此时间已有授课安排' });
    }
    res.status(500).json({ error: '创建授课计划失败', message: error.message });
  }
};

// 更新授课计划
const updatePlan = async (req, res) => {
  try {
    // 如果更新时间相关字段，需要检查冲突
    if (req.body.cadreId || req.body.classDate || req.body.classTime) {
      const currentPlan = await Plan.findById(req.params.id);
      if (!currentPlan) {
        return res.status(404).json({ error: '授课计划不存在' });
      }

      const cadreId = req.body.cadreId || currentPlan.cadreId;
      const classDate = req.body.classDate || currentPlan.classDate;
      const classTime = req.body.classTime || currentPlan.classTime;

      const conflictPlan = await Plan.findOne({
        _id: { $ne: req.params.id },
        cadreId: cadreId,
        classDate: classDate,
        classTime: classTime,
        teachingStatus: { $nin: ['已取消'] }
      });

      if (conflictPlan) {
        return res.status(400).json({ error: '该干部在此时间已有授课安排' });
      }
    }

    const plan = await Plan.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    )
      .populate('cadreId')
      .populate('universityId')
      .populate({
        path: 'cadreId',
        populate: {
          path: 'unitId',
          select: 'name shortName'
        }
      });
    
    if (!plan) {
      return res.status(404).json({ error: '授课计划不存在' });
    }
    
    res.json({
      data: plan,
      message: '更新授课计划成功'
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      return res.status(400).json({ error: '数据验证失败', message: error.message });
    }
    res.status(500).json({ error: '更新授课计划失败', message: error.message });
  }
};

// 删除授课计划
const deletePlan = async (req, res) => {
  try {
    const plan = await Plan.findByIdAndDelete(req.params.id);
    
    if (!plan) {
      return res.status(404).json({ error: '授课计划不存在' });
    }
    
    res.json({ message: '授课计划删除成功' });
  } catch (error) {
    res.status(500).json({ error: '删除授课计划失败', message: error.message });
  }
};

// 获取本周授课计划
const getThisWeekPlans = async (req, res) => {
  try {
    if (req.app.locals.isMongoConnected && req.app.locals.isMongoConnected()) {
      const now = new Date();
      const startOfWeek = new Date(now);
      startOfWeek.setDate(now.getDate() - now.getDay());
      startOfWeek.setHours(0, 0, 0, 0);

      const endOfWeek = new Date(startOfWeek);
      endOfWeek.setDate(startOfWeek.getDate() + 6);
      endOfWeek.setHours(23, 59, 59, 999);

      const plans = await Plan.find({
        classDate: {
          $gte: startOfWeek,
          $lte: endOfWeek
        }
      })
        .populate('cadreId', 'name position')
        .populate('universityId', 'schoolName')
        .sort({ classDate: 1, classTime: 1 });

      res.json({
        data: plans,
        message: '获取本周授课计划成功'
      });
    } else {
      // 返回模拟数据
      const mockData = [
        {
          _id: '1',
          classDate: new Date('2025-06-15'),
          classTime: '09:00-11:00',
          courseName: '新时代党的建设总要求',
          cadreId: { name: '李明', position: '司长' },
          universityId: { schoolName: '清华大学' },
          teachingStatus: '计划中'
        },
        {
          _id: '2',
          classDate: new Date('2025-06-18'),
          classTime: '14:00-16:00',
          courseName: '教育现代化2035规划解读',
          cadreId: { name: '王芳', position: '副司长' },
          universityId: { schoolName: '北京大学' },
          teachingStatus: '计划中'
        }
      ];
      res.json({
        data: mockData,
        message: '获取本周授课计划成功'
      });
    }
  } catch (error) {
    res.status(500).json({ error: '获取本周授课计划失败', message: error.message });
  }
};

module.exports = {
  getAllPlans,
  getPlanById,
  createPlan,
  updatePlan,
  deletePlan,
  getThisWeekPlans
};
